import {PlatformConfig} from '/@/api/sys/model/tenantModel';
import {PLATFORM_CONFIG_KEY, TENANT_INIT_ERROR_KEY} from '/@/enums/cacheEnum';
import {getCacheByDynKey, setCacheByDynKey} from '/@/utils/cache/index'
import {useMessage} from '/@/hooks/web/useMessage';
import {getPublicConfig} from '/@/views/system/config/config.api';
import {useGlobSetting} from '/@/hooks/setting';

const globSetting = useGlobSetting();
/**
 * 租户解析结果
 */
export interface TenantParseResp {
  // 租户id
  id?: string;
  // 只有两种情况 site/s{xx} 或者 admin(id = 1)
  baseUrl?: string;
}


enum SiteUrlPre {
  SITE = 'site',
}


/**
 * 平台租户-获取租户配置
 */
export function getPlatformConfig() {
  return getCacheByDynKey<PlatformConfig>(PLATFORM_CONFIG_KEY);
}


/**
 * 初始化配置
 */
export async function initPlatformConfig() {
  // let url = window.location.hostname;
  // const levelDomain = url.split(".")[0]
  // console.log("levelDomain: ", levelDomain);
  setCacheByDynKey(PLATFORM_CONFIG_KEY, {});

  const data = await getPublicConfig()
  // ConfigKey
  const configValue = { 
    ...data.webSite, 
    ...data.copyright, 
    ldpConnectList: data.ldpConnectList
  }
  setCacheByDynKey(PLATFORM_CONFIG_KEY, configValue);
}

/**
 * 检查租户的错误信息
 */
export const checkWebSiteError = () => {
  const { createMessage } = useMessage()
  const errorInfo = getCacheByDynKey(TENANT_INIT_ERROR_KEY)
  if (errorInfo) {
    // setCacheByDynKey(TENANT_INIT_ERROR_KEY, '');
    // createMessage.error('未知租户')
    // throw new Error('未知租户')
  }
}

export const getSiteBaseUrl = (tenantId) => {
  if (tenantId && tenantId !== '') {
    return `/${SiteUrlPre.SITE}/${tenantId}` 
  }
  return ''
}

/**
 * 获取租户id, 如果是admin, 则租户id为1
 */
export const parseTenantUrl = () : TenantParseResp => {
 
  const resp : TenantParseResp = {
    id: '-1',
    baseUrl: ''
  }
  const path = window.location.pathname
  console.log("path: ", path);
  const tenantUrlPre = path.split('\/')[1] //

  const tenantId = path.split('\/')[2]
  console.log('tenantId: ', tenantId)
  // 验证是否以site开头, 且其余为数字
  if (tenantUrlPre && tenantUrlPre.startsWith(SiteUrlPre.SITE) && !isNaN(Number(tenantId))) {
    resp.id = tenantId.replace('s', '')
    resp.baseUrl = getSiteBaseUrl(tenantId)
  }
  console.log("tenantInfo: ", resp);
  const tenantConfig = getCacheByDynKey<PlatformConfig>(PLATFORM_CONFIG_KEY)
  tenantConfig.tenantId = resp.id
  setCacheByDynKey(PLATFORM_CONFIG_KEY, tenantConfig);

  return resp
}

